package seeqpod;

import java.util.ArrayList;

public class SearchSeeqResultsThread extends Thread {

    private String query;
    private String KEY;
    private int startIndex;
    private int numResults;
    private SeeqPodTrack[] trackarray = null;

    public SearchSeeqResultsThread(String Query, String key, int StartIndex, int NumResults) {
        query = Query;
        KEY = key;
        startIndex = StartIndex;
        numResults = NumResults;
    }

    SeeqPodTrack[] getTracks() {
        return trackarray;
    }

    @Override
    public void run() {

        ArrayList<SeeqPodTrack> tracklist = new ArrayList<SeeqPodTrack>(numResults);
        InOut io = new InOut();
        System.out.println("http://www.seeqpod.com/api/v0.2/" + KEY + "/music/search/" + query + "/" + startIndex + "/10");
        String results = io.readData(io.getURL("http://www.seeqpod.com/api/v0.2/" + KEY + "/music/search/" + query + "/" + startIndex + "/1"));

        int total = Integer.parseInt(results.substring(results.indexOf("total=\"") + 7, results.indexOf("\" prev")));
        SearchSeeqResultThread[] ssrta = new SearchSeeqResultThread[numResults];

        for (int i = 0; tracklist.size() < total && i < numResults; i++) {
            ssrta[i] = new SearchSeeqResultThread(query, SeeqPod.KEY, i + startIndex);
            ssrta[i].start();
        }

        for (int i = 0; i < numResults; i++) {
            try {
                ssrta[i].join();
                tracklist.add(ssrta[i].getTrack());
            } catch (InterruptedException ex) {
            } catch (NullPointerException ex) {
            }
        }

        numResults = tracklist.size();
        trackarray = new SeeqPodTrack[numResults];
        for (int i = 0; i < numResults; i++) {
            trackarray[i] = tracklist.get(i);
        }


    }
}
